<?php
session_start();
require './../libs/pdo_database.php';
require './../forum_support/function.php';
require './../utils/utils.php';
require './../wog_act_config.php';

class wog_account
{
    static $db;
    static $tableName = 'wog_accounts';

    public function __construct()
    {
        $pdo = new PDODatabase();
        self::$db = $pdo->connect();
    }

    /**
     * @param $username
     */
    static function findOneByUsername($username)
    {
        if (!$username) {
            return false;
        }
        $find = self::$db->get(self::$tableName, '*', ['username' => $username]);
        $err = self::$db->error();
        return ($err && $err[1]) || !$find ? false : $find;
    }

    /**
     * 密码md5
     * @param $pwd
     * @return string
     */
    static function passwordMD5($pwd)
    {
        global $wog_array;
        return md5($pwd . $wog_array['password_salt']);

    }

    /**
     * 创建用户账号
     */
    public function create($username, $password)
    {
        global $DB_site, $wog_array;
        $find = self::findOneByUsername($username);
        if ($find) {
            return apiResArray(0, '用户名已存在');
        }
        $has_password = self::passwordMD5($password);
        $save_id = self::$db->insert(self::$tableName, [
            'username' => $username,
            'password' => $has_password
        ]);
        $err = self::$db->error();
        if (!$save_id || ($err && $err[1])) {
            return apiResArray(0, '注册失败', $err ?: null);
        }
        return apiResArray(1, '注册成功');
    }

    /**
     * 登录
     * @return array|void
     */
    public function login($username, $password, $autoLogin = false)
    {
        $check = self::$db->has(self::$tableName, ['username' => $username]);
        if (!$check) {
            return apiResArray(0, '无此账号');
        }
        $find = self::findOneByUsername($username);
        $password_hash = !$autoLogin ? self::passwordMD5($password) : $password;
        if ($find['password'] !== $password_hash) {
            return apiResArray(0, '密码不正确');
        }
        $p_ip = get_ip();
        $last_login_time = time();
        $update = self::$db->update(self::$tableName, ['#last_login_time' => $last_login_time, 'last_ip' => $p_ip], ['id' => $find['id']]);
        unset($p_ip);
        if ($update) {
            $_SESSION['wog_acid'] = $find['id'];
            $_SESSION['wog_ac_login_time'] = $last_login_time;
            setcookie('wog_acid', $find['id']);
            setcookie('wog_login_time', $last_login_time);
            return apiResArray(1, '登录成功', ['id' => $_SESSION['wog_acid']]);
        } else {
            return apiResArray(0, '登录失败', self::$db->error()[2]);
        }
    }

    /**
     * 自动登录
     * @param $account
     * @return array|void
     */
    public function autoLogin($account, $last_login_time)
    {
        if (empty($account) || empty($last_login_time)) {
            return;
        }
        $user = self::$db->get(self::$tableName, ['id' => $account]);
        if (empty($user) && $user['last_login_time'] == $last_login_time) {
            return $this->login($user['username'], $user['password'], true);
        } else {
            return apiResArray(-1, '未登录');
        }
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout()
    {
        $_SESSION = array();
        session_destroy();
        $cookies = $_COOKIE;
        foreach ($cookies as $k => $v) {
            setcookie($k, null);
        }
        cookie_clean();
        return apiResArray(1, '退出成功');
    }

    /**
     * 绑定游戏角色，将改变之前用wog_player表的d_name登录的方式
     * @param $user_id
     * @param $p_name
     * @param $p_password
     * @return array
     */
    public function bindPlaying($user_id, $password, $p_name, $p_password)
    {
        global $wog_array;
        if (empty($user_id)) {
            return apiResArray(-1, '未登录');
        }
        $account = self::$db->get(self::$tableName, '*', ['id' => $user_id]);
        if (empty($account)) {
            return apiResArray(0, '账号错误，请联系管理员');
        }
        $findCountPlayer = self::$db->count('wog_player', ['user_id' => $user_id]);
        if ($findCountPlayer >= $wog_array['player_num']) {
            return apiResArray(0, '账号已达到绑定上限');
        }
        if (!isset($p_name) || !isset($p_password)) {
            return apiResArray(0, '游戏角色名称和对应密码不能为空');
        }
        $findPlayer = self::$db->get('wog_player', '*', ['p_name' => $p_name]);
        if (empty($findPlayer)) {
            return apiResArray(0, '查无此角色');
        }
        if ((int)$findPlayer['user_id'] > 0) {
            return apiResArray(0, '角色已有绑定账号', $findPlayer);
        }
        $updatePlayer = self::$db->update('wog_player', ['user_id' => $user_id], ['p_id' => $findPlayer['p_id']]);
        $updateAccount = self::$db->update(self::$tableName, ['player_num' => $account['player_num'] + 1]);
        return apiResArray(1, '绑定成功');
    }

    /**
     * 根据ID查询用户信息和名下所有角色
     * @param $user_id
     * @return array|void
     */
    public function findAndPlayer($user_id)
    {
        if (empty($user_id)) {
            return apiResArray(0, '无查询条件');
        }
        $result = self::$db->get(self::$tableName, [
            '[>]wog_player(p)' => ['id' => 'user_id'],
            '[>]wog_group_main(g)' => ['p.p_g_id' => 'g_id'],
        ], [
            'id',
            'username',
            'player' => [
                [
                    'p.p_id',
                    'p.p_name',
                    'p.p_password',
                    'p.p_lv',
                    'p.at',
                    'p.df',
                    'p.mat',
                    'p.mdf',
                    'p.s_property',
                    'p.p_ipadd',
                    'p.str',
                    'p.life',
                    'p.vit',
                    'p.smart',
                    'p.agi',
                    'p.hp',
                    'p.sp',
                    'p.spmax',
                    'p.p_sat_name',
                    'p.hpmax',
                    'p.ch_id',
                    'p.p_money',
                    'p.p_lv',
                    'p.p_exp',
                    'p.p_nextexp',
                    'p.p_win',
                    'p.p_lost',
                    'p.p_sex',
                    'p.i_img',
                    'p.p_img_url',
                    'p.p_img_set',
                    'p.p_act_time',
                    'p.p_cdate',
                    'p.p_online_time',
                    'p.p_bbsid',
                    'p.p_pk_s',
                    'p.p_pk_money',
                    'p.p_birth',
                    'p.p_place',
                    'p.au',
                    'p.be',
                    'p.base_str',
                    'p.base_agi',
                    'p.base_life',
                    'p.base_vit',
                    'p.base_smart',
                    'p.base_au',
                    'p.base_be',
                    'p.p_bank',
                    'p.p_bag',
                    'p.p_depot',
                    'p.p_lock',
                    'p.p_g_id',
                    'p.t_id',
                    'p.p_attempts',
                    'p.p_lock_time',
                    'p.p_st',
                    'g.g_name',
                    'g.g_lv',
                ]
            ]
        ], ['id' => $user_id]);
        $err = self::$db->error();
        if ($err[1]) {
            return apiResArray(0, '错误', $err[2]);
        } else if ($result) {
            return apiResArray(1, '查询成功', $result);
        }
    }

    /**
     * 检测是否登录
     * @param $user_id
     * @param $login_time
     * @return array
     */
    public function checkLogin($user_id, $login_time)
    {
        return $this->autoLogin();
    }
}